const mongoose = require('mongoose')
const { Brand } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const brandCollection = mongoose.model('banner', Brand)

function insertBrand (banner) {
    return new Promise((resolve, reject) => {
        brandCollection.find({}).then(res => {
            if (res.length) {
                if (res[0].bannerList.includes(banner)) {
                    reject('已经存在这个品牌')
                    return
                }
                brandCollection.updateOne({ name: 'sport' }, {
                    $push: {
                        bannerList: banner
                    }
                }, {
                    multi: true
                }).then(res => {
                    resolve('品牌:' + banner + '添加成功!')
                })
            } else {
                const record = new brandCollection({ name: 'sport', categoryList: [banner] })
                record.save().then(res => {
                    resolve('品牌:' + banner + '添加成功!')
                })
            }
        })
    })
}

function readBrand () {
    return new Promise((resolve, reject) => {
        brandCollection.findOne({}).then(res => {
            if (res) {
                resolve(res.bannerList)
            } else {
                resolve([])
            }
        }).catch(err => {
            reject(err)
        })
    })
}

function modifyBrandList (brand, newval) {
    return new Promise(resolve => {
        brandCollection.updateOne({
            bannerList: brand
        }, {
            $set: {
                'bannerList.$': newval
            }
        }).then(res => {
            if (res.modifiedCount) {
                resolve('修改品牌成功')
            } else {
                resolve('没有找到品牌')
            }
        })
    })
}

function removeBrandList (brand) {
    return new Promise((resolve, reject) => {
        brandCollection.findOne({ bannerList: brand }).then(res => {
            if (res) {
                brandCollection.updateOne({ name: 'sport' }, {
                    $pull: {
                        bannerList: brand
                    }
                }).then(() => {
                    resolve('移除' + brand + '品牌成功')
                }, () => {
                    reject('移除' + brand + '品牌失败')
                })
            } else {
                reject(brand + '品牌不存在')
            }
        })
    })
}

module.exports = {
    insertBrand,
    readBrand,
    modifyBrandList,
    removeBrandList
}
